import { Consumer } from '@es-tool/core'

/**
 * Page
 * @author LL
 * @date 2022-01-11 上午 10:06
 **/
export class Page<T> {
    /**
     * 当前页
     * @type number
     */
    public currentPage: number
    /**
     * 页大小
     * @type number
     */
    public pageSize: number
    /**
     * 总页数
     * @type number
     */
    public total: number
    /**
     * 列表数据
     * @type Record<string, any>
     */
    public list: T[]

    private configChangeConsumer: Consumer<Page<T>>

    constructor(currentPage: number = 1, pageSize: number = 20, total: number = 0, list: T[] = []) {
        this.currentPage = currentPage
        this.pageSize = pageSize
        this.total = total
        this.list = list
    }

    public static buildQueryPage<T>(currentPage: number, pageSize: number): Page<T> {
        currentPage = Math.max(currentPage, 1)
        pageSize = Math.max(pageSize, 1)
        return new Page<T>(currentPage, pageSize)
    }

    public buildResponsePage(list: T[], total: number): Page<T> {
        this.list = list ?? []
        this.total = Math.max(total, 0)
        return this
    }

    public setCurrentPage(currentPage: number) {
        this.currentPage = currentPage
        this.configChangeConsumer?.(this)
    }

    public setPageSize(pageSise: number) {
        this.pageSize = pageSise
        this.configChangeConsumer?.(this)
    }

    /**
     * pageSize 和 currentPage 发生变化时的回调 {@link setCurrentPage} {@link setPageSize}
     * @param consumer 消费者
     */
    public onConfigChange(consumer: Consumer<Page<T>>) {
        this.configChangeConsumer = consumer
    }

    skip(): number {
        return (this.currentPage - 1) * this.pageSize
    }
}
